// src/api/userApi.js
import axiosInstance from './axiosInstance';

// 登录接口
export const login = async (account, password) => {
  try {
    // 发送POST请求，传递用户名和密码
    const response = await axiosInstance.post('/login', {
      account,
      password,
    });
    console.log(response);
  // 检查响应状态
  if (response?.data?.code === 200 && response?.data?.status) {
    // 如果登录成功，返回用户数据（userId）
    console.log(response.data.data);
    return { success: true, data: response.data.data };
  } else {
    // 登录失败，返回错误消息
    throw new Error(response?.data?.message || '登录失败');
  }
  } catch (error) {
  // 捕获错误并打印
  console.error('登录请求失败:', error);
  return { success: false, error: error.message || '登录失败，请稍后再试' };
  }
};

// 获取主页帖子信息
export const getHome = async (userId) => {
  try {
    const response = await axiosInstance.get('/txq', { params: { userId } });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 获取我的收藏
export const getMyCollection = async (userId) => {
  try {
    const response = await axiosInstance.get('txq/home/collections', { params: { userId }  });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;

    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 获取我的点赞
export const getMyLiked = async (userId) => {
  try {
    const response = await axiosInstance.get('/txq/home/likes', { params: { userId }  });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 获取关注数
export const getFollowCount = async (userId) => {
  try {
    const response = await axiosInstance.get('/getFollowCount', { params: { userId }  });
    console.log(response);
    if (response.data) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 获取粉丝数
export const getFanCount = async (userId) => {
  try {
    const response = await axiosInstance.get('/getFanCount', { params: { userId }  });
    console.log(response);
    if (response.data) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};


// 获取关注列表
export const getFollwers = async (userId) => {
  try {
    const response = await axiosInstance.get('/txq/home/follow', { params: { userId }  });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 获取粉丝列表
export const getFans = async (userId) => {
  try {
    const response = await axiosInstance.get('/txq/home/fans', { params: { userId }  });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 获取热门话题
export const getHot = async (userId) => {
  try {
    const response = await axiosInstance.get('/interest/search', { params: { userId } });
    console.log('Response:', response); // 打印响应以确认格式
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } catch (error) {
    console.error('Error fetching hot topics:', error); // 明确错误信息
    throw error;
  }
};

// 设置查看个人信息
export const getMyprofile = async (userId) => {
  try {
    const response = await axiosInstance.get('/txq/home/settings', { params: { userId } });
    console.log(response.data); // 打印响应体

    // 检查响应是否有效，并获取数据
    if (response.data && response.data.status === true && response.data.data) {
      return response.data.data; // 返回用户的个人信息对象
    } else {
      throw new Error('Invalid data format'); // 抛出错误提示
    }
  } catch (error) {
    console.error('Error fetching user profile:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

//关键词搜索话题 
export const searchTopic = async (keywords,userId) => {
  try {
    const response = await axiosInstance.get('/searchinterest', { params: { keywords,userId } });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

//关键词搜索用户
export const searchUser = async (keywords,userId) => {
  try {
    const response = await axiosInstance.get('/selectuser', { params: { keywords,userId}  });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

//关键词搜索帖子 实时
export const searchPostBytime = async (keywords,userId) => {
  try {
    const response = await axiosInstance.get('/searchblog', {params:{keywords,userId}});
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

//关键词搜索帖子 热度
export const searchPostByHot = async (keywords, userId) => {
  try {
    const response = await axiosInstance.get('/searchblog/hot', {
      params: { keywords, userId },
    });
    console.log(response);
    if (response.data && Array.isArray(response.data.data)) {
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } catch (error) {
    console.error('Error fetching hot posts:', error);
    throw error;
  }
};

//点击话题跳转+对应帖子 实时  
export const searchTopicDetail = async (interestId,userId) => {
  try {
    const response = await axiosInstance.get('/searchblogByinterest', {params:{interestId,userId}});
    if (response.data) {
      console.log(response.data);
      return response.data.data;
    } else {
      throw new Error('Invalid data format');
    }
  } 
  catch (error) {
    console.error('Error fetching users:', error);
    throw error;  // 如果有错误，抛出错误
  }
};

// 注册接口
export const register = async (account, password) => {
  try {
    // 发送POST请求，传递用户名和密码
    const response = await axiosInstance.post('/register', {
      account,
      password,
    });
    console.log(response);
  // 检查响应状态
  if (response?.data?.code === 200 && response?.data?.status) {
    // 如果注册成功，返回用户数据（userId）
    return { success: true, data: response.data.data };
  } else {
    // 注册失败，返回错误消息
    throw new Error(response?.data?.message || '注册失败');
  }
  } catch (error) {
  // 捕获错误并打印
  console.error('注册请求失败:', error);
  return { success: false, error: error.message || '注册失败，请稍后再试' };
  }
};

// 更新用户信息的接口
export const updateUserProfile = async (userId, account, password, sex, signature, image) => {
  try {
    const formData = new FormData();
    formData.append('userId', userId);
    formData.append('account', account);
    formData.append('password', password);
    formData.append('sex', sex);
    formData.append('signature', signature);
    
    if (image) {
      formData.append('image', image);
    }

    const response = await axiosInstance.post('/updateuser', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    if (response.data && response.data.status === true) {
      console.log('Response data:', response.data); // 打印返回的数据进行调试
      return response.data; 
    } else {
      console.error('Backend response:', response.data); // 打印错误信息
      throw new Error('修改失败');
    }
  } catch (error) {
    console.error('Error updating user profile:', error);
    throw error;  
  }
};


// 获取个人主页帖子信息
export const getMyPosts = async (userId, visitorId) => {
  try {
      const response = await axiosInstance.get('/txq/home', { 
          params: { 
              userId, 
              visitorId // 添加访问者 ID
          } 
      });
      console.log(response); // 用于调试输出完整的数据结构

      // 根据后端返回的数据结构进行检查
      if (response.data && response.data.code === 200) {
          return response.data.data.userBlogs; // 返回 userBlogs 数组
      } else {
          throw new Error('无效的数据格式');
      }
  } catch (error) {
      console.error('获取用户帖子时出错:', error);
      throw error; // 如果有错误，抛出错误
  }
};

// 根据帖子id获取帖子详情
export const getBlogById = async (blogId, userId) => {
  try {
      const response = await axiosInstance.get('/blog', { 
          params: { 
              blogId, 
              userId // 添加 userId
          } 
      });
      if (response.data && response.data.code === 200) {
          return response.data.data; // 返回成功获取到的帖子数据
      } else {
          throw new Error(response.data.message || '查询失败');
      }
  } catch (error) {
      console.error('获取帖子失败:', error);
      throw error; // 抛出错误
  }
};


// 加载用户资料
export const loadUserProfile = async (userId, setUserProfile) => {
  try {
      const profileData = await getMyprofile(userId); // 替换为实际的数据获取函数
      // 在这里处理获取到的资料数据，例如设置到状态中
      setUserProfile(profileData);
  } catch (error) {
      console.error('加载用户资料失败:', error);
  }
};

// 收藏接口
export const collect = async (userId, interestId) => {
  try {
    const response = await axiosInstance.post('/collect', {
      userId,
      interestId,
    });
    console.log(response);
    if (response?.data?.code === 200) {
      return { success: true, message: response.data.message };
    } else {
      throw new Error(response?.data?.message || '收藏失败');
    }
  } catch (error) {
    console.error('收藏请求失败:', error);
    return { success: false, error: error.message || '收藏失败，请稍后再试' };
  }
};

// 取消收藏接口
export const uncollect = async (userId, interestId) => {
  try {
    const response = await axiosInstance.post('/uncollect', {
      userId,
      interestId,
    });
    console.log(response);
    if (response?.data?.code === 200) {
      return { success: true, message: response.data.message };
    } else {
      throw new Error(response?.data?.message || '取消收藏失败');
    }
  } catch (error) {
    console.error('取消收藏请求失败:', error);
    return { success: false, error: error.message || '取消收藏失败，请稍后再试' };
  }
};

// 点赞接口
export const like = async (userId, blogId) => {
  try {
      const response = await axiosInstance.post('/like', {
          userId,
          blogId,
      });
      console.log(response);
      if (response?.data?.code === 200) {
          return { success: true, message: response.data.message };
      } else {
          throw new Error(response?.data?.message || '点赞失败');
      }
  } catch (error) {
      console.error('点赞请求失败:', error);
      return { success: false, error: error.message || '点赞失败，请稍后再试' };
  }
};

// 取消点赞接口
export const unlike = async (userId, blogId) => {
  try {
      const response = await axiosInstance.post('/unlike', {
          userId,
          blogId,
      });
      console.log(response);
      if (response?.data?.code === 200) {
          return { success: true, message: response.data.message };
      } else {
          throw new Error(response?.data?.message || '取消点赞失败');
      }
  } catch (error) {
      console.error('取消点赞请求失败:', error);
      return { success: false, error: error.message || '取消点赞失败，请稍后再试' };
  }
};

// 关注接口
export const follow = async (followerId, followeeId) => {
  try {
      const response = await axiosInstance.post('/follow', {
          followerId,
          followeeId,
      });
      console.log(response);
      if (response?.data?.code === 200) {
          return { success: true, message: response.data.message };
      } else {
          throw new Error(response?.data?.message || '关注失败');
      }
  } catch (error) {
      console.error('关注请求失败:', error);
      return { success: false, error: error.message || '关注失败，请稍后再试' };
  }
};

// 取消关注接口
export const unfollow = async (followerId, followeeId) => {
  try {
      const response = await axiosInstance.post('/unfollow', {
          followerId,
          followeeId,
      });
      console.log(response);
      if (response?.data?.code === 200) {
          return { success: true, message: response.data.message };
      } else {
          throw new Error(response?.data?.message || '取消关注失败');
      }
  } catch (error) {
      console.error('取消关注请求失败:', error);
      return { success: false, error: error.message || '取消关注失败，请稍后再试' };
  }
};

// 参与用户接口
export const getParticipants = async (interestId) => {
  try {
      const response = await axiosInstance.get('/participants', {params:{interestId}});
      console.log('participants:'+response.data);
      if (response?.data?.code === 200) {
          return response.data;
      } else {
          throw new Error(response?.data?.message || '参与用户请求失败失败');
      }
  } catch (error) {
      console.error('参与用户请求失败:', error);
      return { success: false, error: error.message || '参与用户请求失败，请稍后再试' };
  }
};

// 获取帖子的评论
export const getCommentsByBlogId = async (blogId) => {
  try {
      const response = await axiosInstance.get('/showcomments', { params: { blogId } }); // 发起 GET 请求
      if (response.data && response.data.code === 200) {
          return response.data.data; // 返回评论数据
      } else {
          throw new Error(response.data.message || '查询失败');
      }
  } catch (error) {
      console.error('获取评论失败:', error);
      throw error; // 抛出错误
  }
};

// 添加新评论
export const addComment = async (userId, blogId, content, repliedId = null) => {
  try {
      const commentData = { userId, blogId, content, repliedId };
      const response = await axiosInstance.post('/comment', commentData); // 发起 POST 请求
      if (response.data && response.data.code === 200) {
          return response.data.message; // 返回成功消息
      } else {
          throw new Error(response.data.message || '发布评论失败');
      }
  } catch (error) {
      console.error('发布评论失败:', error);
      throw error; // 抛出错误
  }
};

// 创建趣点
export const createInterest = async (userId, name, description, image) => {
  try {
    // 创建 FormData 对象来上传数据，包括图片
    const formData = new FormData();
    formData.append('userId', userId);
    formData.append('name', name);
    formData.append('description', description);
    
    // 如果有图片文件，则将其添加到 FormData 中
    if (image) {
      formData.append('image', image);
    }

    // 使用 POST 请求发送数据到后端接口
    const response = await axiosInstance.post('/build', formData, {
      headers: {
        'Content-Type': 'multipart/form-data', // 设置请求头为 multipart/form-data
      },
    });

    // 调试输出响应数据
    console.log(response);

    // 检查响应是否成功
    if (response.data && response.data.code === 200) {
      // 如果成功，返回成功的消息或数据
      return response.data.data[response.data.data.length - 1];
    } else {
      throw new Error(response.data.message || '创建趣点失败');
    }
  } catch (error) {
    console.error('创建趣点时出错:', error);
    throw error; // 如果有错误，抛出错误
  }
};

// 发布帖子接口
export const createBlog = async (image, interestId, userId, description) => {
  try {
    // 创建 FormData 对象来上传数据，包括图片
    const formData = new FormData();
    formData.append('interestId', interestId); // 话题 ID
    formData.append('userId', userId);         // 用户 ID
    formData.append('description', description); // 帖子描述

    // 如果有图片文件，则将其添加到 FormData 中
    if (image) {
      formData.append('image', image); // 上传的图片文件
    }

    // 发送 POST 请求到后端接口
    const response = await axiosInstance.post('/postblog', formData, {
      headers: {
        'Content-Type': 'multipart/form-data', // 设置请求头为 multipart/form-data
      },
    });

    // 输出响应数据（调试用）
    console.log('发布帖子响应:', response);

    // 检查响应是否成功
    if (response.data && response.data.code === 200) {
      // 如果成功，返回成功的消息或数据
      return { success: true, message: response.data.message || '帖子发布成功' };
    } else {
      // 处理后端返回的错误消息
      throw new Error(response.data.message || '帖子发布失败');
    }
  } catch (error) {
    console.error('发布帖子请求失败:', error);
    // 统一返回失败的结构
    return { success: false, error: error.message || '帖子发布失败，请稍后再试' };
  }
};

//删除帖子
export const deleteBlog = async (blogId) => {
  try {
    const response = await axiosInstance.delete('/deleteblog', {params:{blogId}});
    console.log(response);
    if (response.data && response.data.code === 200) {
      return { success: true, message: response.data.message };
    }
    else {
      throw new Error(response.data.message || '删除帖子失败');
    }
  } catch (error) {
    console.error('删除帖子请求失败:', error);
    return { success: false, error: error.message || '删除帖子失败，请稍后再试' };
  }
};



